<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="敏感词">
          <el-input v-model="searchForm.words" placeholder="请输入敏感词"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable @change="handleTypeChange" style="width: 120px">
            <el-option key="" label="全部" value=""></el-option>
            <el-option key="1" label="黑名单" value="1"></el-option>
            <el-option key="2" label="白名单" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>

    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
          stripe
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          row-key="id">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="words" label="敏感词" />
        <el-table-column prop="type" label="类型">
          <template v-slot="scope">
            <span :class="{ 'blacklist': scope.row.type === 1, 'whitelist': scope.row.type === 2 }">
              {{ scope.row.type === 1 ? '黑名单' : '白名单' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)" disabled></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 弹窗部分 -->
    <el-dialog title="敏感词信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="words" label="敏感词">
          <el-input v-model="data.form.words" placeholder="请输入敏感词"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="类型">
          <el-select v-model="data.form.type" placeholder="请选择类型" clearable>
            <el-option key="1" label="黑名单" value="1" />
            <el-option key="2" label="白名单" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";

const searchForm = reactive({
  words: '',
  type: ''
});

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  ids: []
});

const selectedTypeLabel = ref('');

const load = () => {
  request.get('/circle/sensitive/words/list', {
    params: {
      words: searchForm.words,
      type: searchForm.type,
      pageNum: data.pageNum,
      pageSize: data.pageSize
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list || [];
      data.total = res.data.total;
      console.log('data.tableData', data.tableData);
    }
  });
};

// 新增
const handleAdd = () => {
  data.form = {};
  data.formVisible = true;
};

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  // 确保 type 是字符串形式
  data.form.type = data.form.type.toString();
  data.formVisible = true;
};

// 保存操作
const save = () => {
  const url = data.form.id ? '/circle/sensitive/words/update' : '/circle/sensitive/words/save';
  const params = {
    words: data.form.words,
    type: data.form.type
  };
  if (data.form.id) {
    params.id = data.form.id;
  }
  request.get(url, {params}).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  }).catch(err => {
    ElMessage.error('操作失败，请检查输入');
    console.error(err);
  });
};

// 删除操作
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/circle/sensitive/words/remove', {params: {id}}).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete("/circle/sensitive/words/batchRemove", {data: {ids: data.ids}}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 选择框变更时
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.words = '';
  searchForm.type = '';
  selectedTypeLabel.value = '';
  load();
};

// 处理类型变化
const handleTypeChange = (value) => {
  switch (value) {
    case '1':
      selectedTypeLabel.value = '黑名单';
      break;
    case '2':
      selectedTypeLabel.value = '白名单';
      break;
    default:
      selectedTypeLabel.value = '';
      break;
  }
};

// 加载数据
load();
</script>

<style scoped>
.card {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.el-table th.el-table__cell.is-leaf {
  background-color: #f8f8f9;
}

.blacklist {
  color: white;
  background-color: red;
  padding: 2px 5px;
  border-radius: 3px;
}

.whitelist {
  color: white;
  background-color: green;
  padding: 2px 5px;
  border-radius: 3px;
}
</style>
